import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQml.Models
import "qrc:/qml/styles" as Styles
import "qrc:/qml/components"

Rectangle {
    id: areaTab
    color: "transparent"

    property var areaModel: GlobalResourceViewModel ? GlobalResourceViewModel.areaOccupancyModel : null
    property var floorOptions: [{ text: "全部楼层", value: null }]
    property int areaDataRevision: 0
    property var filteredAreas: []
    property int filteredAreaCount: 0

    function bumpAreaRevision() { areaDataRevision++; }

    function matchesAreaFilters(areaId, floor, isOccupied, isThirdParty) {
        const selectedFloor = floorFilter ? floorFilter.currentValue : null;
        if (selectedFloor !== null && floor !== selectedFloor) {
            return false;
        }

        const statusIndex = statusFilter ? statusFilter.currentIndex : 0;
        if (statusIndex === 1 && !isOccupied) return false;
        if (statusIndex === 2 && isOccupied) return false;

        const typeIndex = typeFilter ? typeFilter.currentIndex : 0;
        if (typeIndex === 1 && isThirdParty) return false;
        if (typeIndex === 2 && !isThirdParty) return false;

        const keyword = searchBar && searchBar.searchText ? searchBar.searchText.toLowerCase() : "";
        if (keyword.length > 0) {
            const idText = areaId ? areaId.toLowerCase() : "";
            if (!idText.includes(keyword)) {
                return false;
            }
        }

        return true;
    }

    function rebuildFilteredAreas() {
        const results = [];
        if (areaModel) {
            for (let i = 0; i < areaModel.rowCount(); i++) {
                const area = areaModel.getAreaData(i);
                if (area && matchesAreaFilters(area.areaId, area.floor, area.isOccupied, area.isThirdParty)) {
                    results.push(area);
                }
            }
        }
        filteredAreas = results;
        filteredAreaCount = results.length;
    }

    function stateText(area) {
        if (!area) return "空闲";
        switch (area.occupationState) {
        case "preOccupied":
            return "预占用";
        case "agvOccupied":
            return "AGV占用";
        case "thirdParty":
            return "第三方占用";
        case "occupied":
            return "已占用";
        default:
            return "空闲";
        }
    }

    function stateColor(area) {
        if (!area || area.occupationState === "idle")
            return Styles.Theme.success;
        switch (area.occupationState) {
        case "preOccupied":
            return Styles.Theme.warning;
        case "thirdParty":
            return Styles.Theme.info;
        default:
            return Styles.Theme.danger;
        }
    }

    function updateFloorOptions() {
        let options = [{ text: "全部楼层", value: null }];
        if (areaModel) {
            let floors = [];
            for (let i = 0; i < areaModel.rowCount(); i++) {
                const area = areaModel.getAreaData(i);
                if (area && floors.indexOf(area.floor) === -1) {
                    floors.push(area.floor);
                }
            }
            floors.sort((a, b) => a - b);
            floors.forEach(floor => {
                options.push({
                    text: floor + "楼",
                    value: floor
                });
            });
        }

        const previousValue = floorFilter ? floorFilter.currentValue : null;
        floorOptions = options;

        if (floorFilter) {
            if (previousValue === null) {
                floorFilter.currentIndex = 0;
            } else {
                const matchedIndex = options.findIndex(item => item.value === previousValue);
                floorFilter.currentIndex = matchedIndex >= 0 ? matchedIndex : 0;
            }
        }
    }

    Connections {
        target: areaModel
        ignoreUnknownSignals: true
        function onModelReset() {
            bumpAreaRevision();
            updateFloorOptions();
            rebuildFilteredAreas();
        }
        function onRowsInserted() {
            bumpAreaRevision();
            updateFloorOptions();
            rebuildFilteredAreas();
        }
        function onRowsRemoved() {
            bumpAreaRevision();
            updateFloorOptions();
            rebuildFilteredAreas();
        }
        function onDataChanged() {
            bumpAreaRevision();
            updateFloorOptions();
            rebuildFilteredAreas();
        }
    }

    Component.onCompleted: {
        updateFloorOptions();
        rebuildFilteredAreas();
    }

    ColumnLayout {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingLarge
        spacing: Styles.Theme.spacingLarge

        // 顶部统计卡片
        Row {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingNormal

            KpiCard {
                width: 200
                height: 100
                title: "区域总数"
                value: GlobalResourceViewModel ? GlobalResourceViewModel.totalAreaCount : 0
                iconSource: "📍"
                accentColor: Styles.Theme.primary
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "已占用区域"
                value: GlobalResourceViewModel ? GlobalResourceViewModel.occupiedAreaCount : 0
                iconSource: "🔒"
                accentColor: Styles.Theme.warning
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "空闲区域"
                value: {
                    if (!GlobalResourceViewModel) return 0;
                    return GlobalResourceViewModel.totalAreaCount - GlobalResourceViewModel.occupiedAreaCount;
                }
                iconSource: "✓"
                accentColor: Styles.Theme.success
                enableValueAnimation: false
            }

            KpiCard {
                width: 200
                height: 100
                title: "第三方区域"
                value: {
                    areaDataRevision;
                    if (!areaModel) return 0;
                    let count = 0;
                    for (let i = 0; i < areaModel.rowCount(); i++) {
                        const area = areaModel.getAreaData(i);
                        if (area && area.isThirdParty) {
                            count++;
                        }
                    }
                    return count;
                }
                iconSource: "🔗"
                accentColor: Styles.Theme.info
                enableValueAnimation: false
            }
        }

        // 筛选栏
        Rectangle {
            Layout.fillWidth: true
            height: 60
            color: Styles.Theme.surface
            radius: Styles.Theme.radiusNormal

            RowLayout {
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                Text {
                    text: "筛选："
                    font.pixelSize: Styles.Theme.fontSizeNormal
                    color: Styles.Theme.textSecondary
                }

                CustomComboBox {
                    id: floorFilter
                    Layout.preferredWidth: 150
                    model: floorOptions
                    textRole: "text"
                    valueRole: "value"
                    currentIndex: 0
                    placeholderText: "全部楼层"
                    onCurrentIndexChanged: rebuildFilteredAreas()
                }

                CustomComboBox {
                    id: statusFilter
                    Layout.preferredWidth: 150
                    model: ["全部状态", "已占用", "空闲"]
                    currentIndex: 0
                    onCurrentIndexChanged: rebuildFilteredAreas()
                }

                CustomComboBox {
                    id: typeFilter
                    Layout.preferredWidth: 150
                    model: ["全部类型", "普通区域", "第三方区域"]
                    currentIndex: 0
                    onCurrentIndexChanged: rebuildFilteredAreas()
                }

                SearchBar {
                    id: searchBar
                    Layout.fillWidth: true
                    placeholderText: "搜索区域ID..."
                    onTextSearched: rebuildFilteredAreas()
                    onCleared: rebuildFilteredAreas()
                }

                ActionButton {
                    text: "刷新"
                    iconSource: "qrc:/icons/refresh.svg"
                    size: "small"
                    onClicked: {
                        if (GlobalResourceViewModel) {
                            GlobalResourceViewModel.refreshAreaData();
                        }
                    }
                }
            }
        }

        // 区域列表
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: Styles.Theme.surface
            radius: Styles.Theme.radiusNormal

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: Styles.Theme.spacingNormal
                spacing: Styles.Theme.spacingNormal

                // 标题栏
                Text {
                    text: "区域占用列表"
                    font.pixelSize: Styles.Theme.fontSizeLarge
                    font.weight: Styles.Theme.fontWeightBold
                    color: Styles.Theme.textPrimary
                }

                // 表头
                Rectangle {
                    Layout.fillWidth: true
                    height: 40
                    color: Styles.Theme.surfaceHeader
                    radius: Styles.Theme.radiusSmall

                    RowLayout {
                        anchors.fill: parent
                        anchors.leftMargin: Styles.Theme.spacingNormal
                        anchors.rightMargin: Styles.Theme.spacingNormal
                        spacing: Styles.Theme.spacingNormal

                        Text { Layout.preferredWidth: 150; Layout.alignment: Qt.AlignVCenter; text: "区域ID"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 150; Layout.alignment: Qt.AlignVCenter; text: "地图名称"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 80; Layout.alignment: Qt.AlignVCenter; text: "楼层"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "类型"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 100; Layout.alignment: Qt.AlignVCenter; text: "占用状态"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Text { Layout.preferredWidth: 200; Layout.alignment: Qt.AlignVCenter; text: "占用者"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                        Item { Layout.fillWidth: true }
                        Text { Layout.preferredWidth: 150; Layout.alignment: Qt.AlignVCenter; text: "操作"; font.pixelSize: Styles.Theme.fontSizeNormal; font.weight: Styles.Theme.fontWeightMedium; color: Styles.Theme.textSecondary }
                    }
                }

                // 区域列表
                Item {
                    Layout.fillWidth: true
                    Layout.fillHeight: true

                    ListView {
                        id: areaListView
                        anchors.fill: parent
                        clip: true
                        spacing: 0
                        boundsBehavior: Flickable.StopAtBounds
                        highlightMoveDuration: 0
                        model: filteredAreas

                        delegate: Rectangle {
                            id: areaListItem
                            width: areaListView.width
                            height: 60
                            radius: Styles.Theme.radiusSmall
                            color: index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate

                            // 平滑的颜色过渡
                            Behavior on color {
                                ColorAnimation { duration: Styles.Theme.animationFast }
                            }

                            RowLayout {
                                anchors.fill: parent
                                anchors.leftMargin: Styles.Theme.spacingNormal
                                anchors.rightMargin: Styles.Theme.spacingNormal
                                spacing: Styles.Theme.spacingNormal

                                Text {
                                    Layout.preferredWidth: 150
                                    Layout.alignment: Qt.AlignVCenter
                                    text: modelData.areaId
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    font.weight: Styles.Theme.fontWeightMedium
                                    color: Styles.Theme.textPrimary
                                    elide: Text.ElideRight
                                }

                                Text {
                                    Layout.preferredWidth: 150
                                    Layout.alignment: Qt.AlignVCenter
                                    text: modelData.mapName
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: Styles.Theme.textSecondary
                                    elide: Text.ElideRight
                                }

                                Text {
                                    Layout.preferredWidth: 80
                                    Layout.alignment: Qt.AlignVCenter
                                    text: modelData.floor + "F"
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: Styles.Theme.textPrimary
                                }

                                Rectangle {
                                    Layout.preferredWidth: 100
                                    Layout.alignment: Qt.AlignVCenter
                                    height: 24
                                    radius: 12
                                    color: modelData.isThirdParty ? Qt.alpha(Styles.Theme.info, 0.2) : Qt.alpha(Styles.Theme.primary, 0.2)
                                    border.width: 1
                                    border.color: modelData.isThirdParty ? Styles.Theme.info : Styles.Theme.primary

                                    Text {
                                        anchors.centerIn: parent
                                        text: modelData.isThirdParty ? "第三方" : "普通"
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        color: modelData.isThirdParty ? Styles.Theme.info : Styles.Theme.primary
                                    }
                                }

                                RowLayout {
                                    Layout.preferredWidth: 100
                                    Layout.alignment: Qt.AlignVCenter
                                    spacing: Styles.Theme.spacingXSmall

                                    Rectangle {
                                        width: 8
                                        height: 8
                                        radius: 4
                                        color: stateColor(modelData)
                                    }

                                    Text {
                                        text: stateText(modelData)
                                        font.pixelSize: Styles.Theme.fontSizeSmall
                                        color: stateColor(modelData)
                                    }
                                }

                                Text {
                                    Layout.preferredWidth: 200
                                    Layout.alignment: Qt.AlignVCenter
                                    text: modelData.occupiedBy
                                    font.pixelSize: Styles.Theme.fontSizeNormal
                                    color: modelData.isOccupied ? Styles.Theme.textPrimary : Styles.Theme.textTertiary
                                    elide: Text.ElideRight
                                }

                                Item { Layout.fillWidth: true }

                                ActionButton {
                                    Layout.preferredWidth: 150
                                    Layout.alignment: Qt.AlignVCenter
                                    text: "强制释放"
                                    size: "small"
                                    buttonType: "danger"
                                    enabled: modelData.isOccupied
                                    onClicked: {
                                        releaseConfirmDialog.areaId = modelData.areaId;
                                        releaseConfirmDialog.floor = modelData.floor;
                                        releaseConfirmDialog.isThirdParty = modelData.isThirdParty;
                                        releaseConfirmDialog.open();
                                    }
                                }
                            }

                            MouseArea {
                                anchors.fill: parent
                                hoverEnabled: true
                                propagateComposedEvents: true
                                onEntered: areaListItem.color = Styles.Theme.surfaceVariant
                                onExited: areaListItem.color = index % 2 === 0 ? Styles.Theme.surface : Styles.Theme.backgroundAlternate
                                onPressed: function(mouse) { mouse.accepted = false; }
                                onClicked: function(mouse) { mouse.accepted = false; }
                            }
                        }

                        ScrollBar.vertical: ScrollBar {
                            policy: ScrollBar.AsNeeded
                        }
                    }

                                        Item {
                        id: emptyStateOverlay
                        anchors.fill: parent
                        readonly property bool hasRawData: {
                            areaDataRevision;
                            return areaModel && areaModel.rowCount() > 0;
                        }
                        visible: !hasRawData || filteredAreas.length === 0

                        Column {
                            anchors.centerIn: parent
                            spacing: Styles.Theme.spacingSmall
                            opacity: 0.8

                            Text {
                                text: emptyStateOverlay.hasRawData ? "没有符合条件的区域" : "暂无区域数据"
                                font.pixelSize: Styles.Theme.fontSizeLarge
                                font.weight: Styles.Theme.fontWeightBold
                                color: Styles.Theme.textSecondary
                                horizontalAlignment: Text.AlignHCenter
                            }

                            Text {
                                text: emptyStateOverlay.hasRawData ? "尝试调整筛选条件或点击刷新" : "等待地图资源加载完成后重试"
                                font.pixelSize: Styles.Theme.fontSizeNormal
                                color: Styles.Theme.textSecondary
                                horizontalAlignment: Text.AlignHCenter
                            }
                        }
                    }
                }
            }
        }
    }

    // 强制释放确认对话框
    ConfirmDialog {
        id: releaseConfirmDialog
        title: "确认强制释放"
        message: "确定要强制释放区域 \"" + areaId + "\" 吗？\n\n此操作将立即解除该区域的占用状态，可能会影响正在执行的任务。"
        confirmText: "强制释放"
        cancelText: "取消"

        property string areaId: ""
        property int floor: 1
        property bool isThirdParty: false

        onAccepted: {
            if (GlobalResourceViewModel) {
                if (isThirdParty) {
                    GlobalResourceViewModel.forceReleaseThirdArea(areaId);
                } else {
                    GlobalResourceViewModel.forceReleaseArea(areaId, floor);
                }
            }
        }
    }

}
